<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="/static/css/cart.css">
</head>
<body>
<div class="container">
    <header>
        <h1>购物车</h1>
        <form class="search-form">
            <input type="text" placeholder="搜索商品">
            <button type="submit">搜索</button>
        </form>
    </header>

    <main>
        <section class="cart-items">
            <h2>购物车商品</h2>
            <div class="cart-actions">
                <label for="selectAll">全选</label>
                <input id="selectAll" type="checkbox">
                <button onclick="deleteSelectedItems()">删除选中</button>
            </div>

            <!-- 使用 JavaScript 渲染购物车商品 -->
            <div id="cart-list"></div>
        </section>

        <section class="checkout-details">
            <h2>结算信息</h2>
            <div class="checkout-summary">
                <div>
                    <span>商品总价</span>
                    <span id="total-price">¥0.00</span>
                </div>
                <div>
                    <span>运费</span>
                    <span>¥0.00</span>
                </div>
                <div>
                    <span>优惠</span>
                    <span>- ¥0.00</span>
                </div>
                <div class="total">
                    <span>实付款</span>
                    <span id="final-price">¥0.00</span>
                </div>
            </div>
            <button id="checkout-button">结算</button>
        </section>
    </main>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const container = document.getElementById('cart-list');
        const selectAll = document.getElementById('selectAll');
        const checkoutButton = document.getElementById('checkout-button');

        let items = []; // 存储购物车数据供后续使用

        fetch('/get/cart_items')
            .then(response => response.json())
            .then(data => {
                items = data;

                items.forEach(item => {
                    const div = document.createElement('div');
                    div.className = 'cart-item';
                    div.innerHTML = `
                <div class="item-shop">
                    <label for="checkbox-${item.ID}">${item.Shopname}</label>
                    <input id="checkbox-${item.ID}" type="checkbox" data-id="${item.ID}">
                </div>
                <div class="item-details">
                    <img src="${item.Image}" alt="商品图片">
                    <div class="item-info"><p>${item.Title}</p></div>
                    <div class="item-specs"><p>种类: ${item.Type}</p></div>
                    <div class="item-price"><span>¥${(item.Price)}</span></div>
                    <div class="item-quantity"><span>数量: ${item.Number}</span></div>
                    <div class="item-actions">
                        <button onclick="deleteCartItem(${item.ID})">删除</button>
                    </div>
                </div>`;
                    container.appendChild(div);
                });

                updateCheckboxes();
                calculateTotalPrice();
            });
        function updateCheckboxes() {
            const checkboxes = document.querySelectorAll('.item-shop input[type="checkbox"]');
            checkboxes.forEach(cb => {
                cb.addEventListener('change', calculateTotalPrice);
            });
        }

        function updateSelectAllState() {
            const checkboxes = document.querySelectorAll('.item-shop input[type="checkbox"]');
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            selectAll.checked = allChecked;
        }

        selectAll.addEventListener('change', function () {
            const checkboxes = document.querySelectorAll('.item-shop input[type="checkbox"]');
            checkboxes.forEach(cb => cb.checked = selectAll.checked);
            calculateTotalPrice();
        });

        function calculateTotalPrice() {
            let total = 0;
            const checkboxes = document.querySelectorAll('.item-shop input[type="checkbox"]');
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const id = cb.dataset.id;
                    const item = items.find(i => i.ID.toString() === id);
                    if (item) total += item.Money;
                }
            });
            document.getElementById('total-price').textContent = `¥${total.toLocaleString()}`;
            document.getElementById('final-price').textContent = `¥${total.toLocaleString()}`;
        }

        checkoutButton.addEventListener('click', function () {
            const checkboxes = document.querySelectorAll('.item-shop input[type="checkbox"]');
            const selectedItems = Array.from(checkboxes)
                .filter(cb => cb.checked)
                .map(cb => cb.dataset.id);

            if (selectedItems.length === 0) {
                alert("请至少选择一个商品");
                return;
            }

            fetch('/confirm_payment', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ item_ids: selectedItems })
            }).then(response => {
                if (response.ok) {
                    window.location.href = "/user/center";
                } else {
                    alert("结算失败，请重试");
                }
            }).catch(err => {
                console.error(err);
                alert("网络请求异常，请检查控制台");
            });
        });

        function deleteCartItem(itemId) {
            fetch(`/delete/item/${itemId}`, {
                method: 'POST'
            }).then(response => {
                if (response.ok) {
                    window.location.reload();
                } else {
                    alert("删除失败");
                }
            });
        }

        function deleteSelectedItems() {
            const checkboxes = document.querySelectorAll('.item-shop input[type="checkbox"]');
            const selectedItems = Array.from(checkboxes)
                .filter(cb => cb.checked)
                .map(cb => cb.dataset.id);

            if (selectedItems.length === 0) {
                alert("请至少选择一个商品");
                return;
            }

            if (!confirm("确定要删除所选项吗？")) return;

            selectedItems.forEach(itemId => {
                fetch(`/delete/item/${itemId}`, {
                    method: 'POST'
                }).then(response => {
                    if (response.ok) {
                        window.location.reload();
                    } else {
                        alert(`商品 ${itemId} 删除失败`);
                    }
                });
            });
        }
    });
</script>
</body>
</html>

    